<template>
  <div class="tree-container">
    <div class="head-top flex-center">
      <el-input v-model="deptName" class="mb-20px" clearable placeholder="请输入">
        <template #suffix>
          <Icon icon="ep:search" />
        </template>
      </el-input>
      <Icon v-if="type === 'dataset'" icon="ep:plus" style="margin-left: 15px;cursor: pointer;" @click="actionParentNode" />
    </div>
    <div class="head-tree">
      <el-scrollbar wrap-class="h-full">
        <el-tree
        ref="treeRef"
        :data="deptList"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        :props="defaultProps"
        default-expand-all
        highlight-current
        node-key="id"
        @node-click="handleNodeClick"
      >
        <template #default="{ node, data }" >
          <div class="custom-tree-node" @mouseenter="handleMouseEnter(data)" @mouseleave="handleMouseLeave()">
              <span :class="['tree-label', {activeNode : data.id === activeNodeId }]">{{ node.label }}</span>
              <span class="tree-actions flex-center" v-show="data.id === hoverNodeId && type === 'dataset'">
                <Icon icon="ep:circle-plus-filled" @click.stop.prevent="actionNode('create', data, node)" v-hasPermi="['multiModel:dataset-type:create']" />
                <Icon icon="ep:remove-filled" style="margin-left: 3px" @click.stop.prevent="removeNode(node, data)" v-hasPermi="['multiModel:dataset-type:delete']" />
                <Icon icon="ep:edit" style="margin-left: 3px" @click.stop.prevent="actionNode('update', data)" v-hasPermi="['multiModel:dataset-type:update']" />
              </span>
          </div>
        </template>
      </el-tree>
      </el-scrollbar>
      
    </div>
    <TreeNodeForm ref="treeFormRef" @success="addParentNode" />
    <DelConfirmDialog ref="delConfirmRef" @confirm="deleteConfirm" />
  </div>
    
</template>

<script lang="ts" setup>
import { ElTree } from 'element-plus'
import * as DeptApi from '@/api/system/dept'
import { defaultProps, handleTree } from '@/utils/tree'
import TreeNodeForm from './TreeNodeForm.vue'
import { DatasetTypeApi } from '@/api/multiModel/datasettype'

defineOptions({ name: 'DeptTree' })

import { propTypes } from '@/utils/propTypes'
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const props = defineProps({
  type: propTypes.string.def(''),
  data: {
    type: Array as PropType<Recordable[]>,
    default: () => []
  }
})

const deptName = ref('')
const deptList = ref<Tree[]>([]) // 树形结构
const treeRef = ref<InstanceType<typeof ElTree>>()

/** 获得部门树 */
const getTree = async () => {
  let res
  if (props.type === 'dataset') {
    res = await DatasetTypeApi.getDatasetTypeList()
  } else {
    res = await DeptApi.getSimpleDeptList()
  }
  deptList.value = []
  deptList.value.push(...handleTree(res))
}

/** 基于名字过滤 */
const filterNode = (name: string, data: Tree) => {
  if (!name) return true
  return data.name.includes(name)
}

// 鼠标点击节点ID
const activeNodeId = ref<number | null>(null)
/** 处理节点被点击 */
const handleNodeClick = async (row: { [key: string]: any }) => {
  if (activeNodeId.value === row.id) return
  activeNodeId.value = row.id
  emits('node-click', row.id, row.name, !row.children || !row.children.length)
}
const emits = defineEmits(['node-click'])

// 鼠标移入节点ID
const hoverNodeId = ref<number | null>(null)
 
const handleMouseEnter = (data: Tree) => {
  if (props.type === 'user') return
  hoverNodeId.value = data.id
};
const handleMouseLeave = () => {
  if (props.type === 'user') return
  hoverNodeId.value = null
};

// 操作节点
const treeFormRef = ref()
const actionNode = (type: string, data:Tree, node:any) => {
  treeFormRef.value.open(type, data)
};
const actionParentNode = () => {
  treeFormRef.value.open('create', {
    id: 0,
    name: '',
    parentId: 0,
    level: 1,
    children: []
  }, true)
}
const currentNode = ref()
const currentData = ref()
const delConfirmRef = ref()
const removeNode = async (node: Node, data: Tree) => {
  delConfirmRef.value.open(data.id, ['是否确定删除选中数据集?'])
  currentNode.value = node
  currentData.value = data
}
/** 删除按钮操作 */
const deleteConfirm = async (id: number) => {
  try {
    await DatasetTypeApi.deleteDatasetType(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    const parent = currentNode.value.parent
    const children: Tree[] = parent.data.children || parent.data
    const index = children.findIndex((d) => d.id === currentData.value.id)
    children.splice(index, 1)
    if (activeNodeId.value === currentData.value.id) {
      if (deptList.value.length) {
        const d = deptList.value[0]
        activeNodeId.value = d.id
        emits('node-click', d.id, d.name)
      }
    }
  } catch {}
}
const addParentNode = (data:Tree) => {
  data = {
    ...data,
    level: 1
  }
  deptList.value.unshift(data)
}
// 首次进入
const initDatasetPage = () => {
  if (deptList.value.length) {
    const d = deptList.value[0]
    activeNodeId.value = d.id
    emits('node-click', d.id, d.name)
  }
}


/** 监听deptName */
watch(deptName, (val) => {
  treeRef.value!.filter(val)
})

/** 初始化 */
onMounted(async () => {
  await getTree()
  initDatasetPage()
})
</script>

<style scoped lang="scss">
.tree-container {
  height: 100%;
  overflow: hidden;
  background-color: #fff;
  border: 1px solid #CDD7D5;
  .head-container {
    // 
  }
  .head-top {
    padding: 16px;
    border-bottom: 1px solid #CDD7D5;
    .el-input {
      margin-bottom: 0;
    }
  }
  .head-tree {
    height: calc(100% - 96px);
    padding: 16px;
    padding-right: 0px;
  }
}
.custom-tree-node {
  width: calc(100% - 24px);
  display: flex;
  align-items: center;
  justify-content: space-between;
  .tree-label {
    width: calc(100% - 50px);
    overflow: hidden !important;
    white-space: nowrap !important;
    text-overflow: ellipsis !important;
  }
  .tree-actions {
    // line-height: 26px;
    margin-right: 16px;
  }
  .activeNode {
    color: var(--el-color-primary)
  }
}
</style>
